﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Polaris.Common.DomainInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Polaris.Common.FilterAttribute
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class UnitOfWorkFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 是否开启事务
        /// </summary>
        public bool IsTransactional { get; set; } = false;

        /// <summary>
        /// 在Action执行前判断是否开启事务
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (IsTransactional)
            {
                var unitOfWork = context.HttpContext.RequestServices.GetRequiredService<IUnitOfWork>();
                //开始事务
                unitOfWork.BeginTransaction();

                context.HttpContext.Items[nameof(IUnitOfWork)] = unitOfWork;
            }

            base.OnActionExecuting(context);

        }

        /// <summary>
        /// 在Action执行后判断是否需要提交事务
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            var _unitOfWork = context.HttpContext.RequestServices.GetRequiredService<IUnitOfWork>();

            // 提交事务
            _unitOfWork.CommitTransaction();
        }
    }
}
